<template>
  <div class="machining" v-loading="loading">
    <header class="machin-head">
      <div class="machin-seach">
        <el-date-picker
            class="date-3"
            type="date"
            v-model="date"
            placeholder="选择日期">
        </el-date-picker>
        <el-select class="select-3 machin-select" v-model="status"  placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.name"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        <el-button class="btn-2" @click="search" >查询</el-button>
        <el-button class="btn-2">导出</el-button>
      </div>
      <div class="machin-btn">
        <el-button class="btn-2" @click="addRecord" v-jurisdiction="'warehouse:process:add'">新建记录</el-button>
      </div>
    </header>
    <div class="machin-content">
      <ztable 
          :tableData='data' 
          :strucs='columns'
          :width="'240'"
          :height="'100%'"
          :isshowOperation="true"
          :border="false"
        >
        <template #default="slotData">
            <el-select 
              v-jurisdiction="'warehouse:process:updateStatus'"
							class="select-3 machin-select" 
							v-model="slotData.rowData.status"  
							placeholder="请选择"
              @change="handleChange($event, slotData.rowData)"
							>
							<el-option
								v-for="i in options"
								:key="i.name"
								:label="i.name"
								:value="i.id">
							</el-option>
						</el-select>
            <el-button @click="handleEditItem(slotData.rowData)" 
              type="text" 
              size="small" 
              class="operation" 
              v-jurisdiction="'warehouse:process:update'"
              >修改</el-button>
            <el-button @click="handleDelItem(slotData.rowData)" 
              type="text" 
              size="small" 
              class="operation" 
              v-jurisdiction="'warehouse:process:del'"
              >删除</el-button>
          </template>
        </ztable>
    </div>

    <zdrawer @handleClose="close" :title="title" v-model="openDrawer">
      <template #body>
        <ztitleBorder title="就诊详情">
            <!-- <div class="tem">
              <div class="tem-title">就诊项目</div>
              <el-select class="select-1" v-model="orderDetailId" placeholder="请选择病历">
                <el-option
                  v-for="item in orderDetail"
                  :key="item.id"
                  :label="item.itemName"
                  :value="item.id">
                </el-option>
            </el-select>
            </div> -->
            <div class="tem">
              <div class="tem-title">病历</div>
              <el-select class="select-1" v-model="medicalHistoryId" placeholder="请选择病历">
                <el-option
                  v-for="item in medicalOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
            </div>
            <div class="tem">
              <div class="tem-title">订单编号</div>
              <el-input placeholder="请输入订单编号" v-model="processOrderCode"  class="input-2"></el-input>
            </div>
            <div class="tem">
              <div class="tem-title">取件人</div>
              <el-select class="select-1" v-model="consigneeId" placeholder="请选择取件人">
                <el-option
                  v-for="item in consigneeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
            </div>
            <div class="tem">
              <div class="tem-title">医生</div>
              <el-select class="select-1" v-model="companyUserId" placeholder="请选择医生">
                <el-option
                  v-for="item in companyUserOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
            </div>
            <div class="tem">
              <div class="tem-title">加工厂</div>
              <el-select class="select-1" v-model="processFactoryId" placeholder="请选择加工厂">
                <el-option
                  v-for="item in processFactoryOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
            </div>
        </ztitleBorder>
        <ztitleBorder title="加工详情">
          <el-table
            :data="details"
            border
            style="width: 100%"
            height="300"
            >
            <el-table-column prop="processingItems" label="加工物品名称" width="180">
              <template #default="scope">
                <el-input placeholder="请输入名称" v-model="scope.row.processingItems"  class="input-2"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="processingFree"
              label="	加工物品价格"
              width="180"
              >
              <template #default="scope">
                <el-input placeholder="请输入价格" v-model="scope.row.processingFree"  class="input-2"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="orderDetailId"
              label="项目"
              width="180"
              >
              <template #default="scope">
                <el-select class="select-1" v-model="scope.row.orderDetailId" placeholder="请选择项目">
                <el-option
                    v-for="item in orderDetail"
                    :key="item.id"
                    :label="item.itemName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              align="right">
              <template #header>
                <el-button class="btn-1" @click="addProcess">新增</el-button>
              </template>
              <template #default="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </ztitleBorder>
      </template>
      <template #footer>
        <el-button class="btn-2" @click="cancel">取消</el-button>
        <el-button class="btn-1" @click="save">保存</el-button>
      </template>
    </zdrawer>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from '@vue/runtime-core';
import ztable from "../../../components/Table/index.vue"
import zdrawer from "../../../components/drawer/drawer.vue"
import ztitleBorder from "../../../components/titleBorder/titleBorder.vue"

import useRequet, { RespData } from "../../../hook/network"
import useConfgin from '../../../hook/getconfig'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'


type OpearBtn = {
	id: string | number,
	name: string | number
}
type OrderDetailType = {
  id: number | string,
  itemName: string,
}
type Process = {
  orderDetailId: string | number,
  processingItems: string,
  processingFree: string | number
}

// 患者计加工
const configID = 542
export default defineComponent({
  name: 'Machin',
  props: {
      id: {
        type: String
      }
  },
  components: {
    ztable,
    zdrawer,
    ztitleBorder
  },
  setup(props, ctx) {
    const route = useRoute()
    const request = useRequet({ path: "" });
    const id = route.params.id
    const list  = reactive({
      date: '',
      status: '',
      data:[],
      columns: <any>[],
      options:[] as OpearBtn[],
      openDrawer: false,
      current: 1,
      size: 10,
      total: 0,
      loading: false,
      medicalOptions: [] as OpearBtn[],
      medicalHistoryId: '',
      processOrderCode: '',
      consigneeId: '',
      consigneeOptions: [] as OpearBtn[],
      companyUserId: '',
      companyUserOptions: [] as OpearBtn[],
      orderDetail: [] as OrderDetailType[],
      orderDetailId: '',
      details: [] as Process[],
      processFactoryId: '',
      processFactoryOptions: [] as OpearBtn[],
      title: '新建计加工',
      id: '',
      customerId: ''
    })

    const rowsList = useConfgin(configID)
    list.columns = rowsList.groupDataList.value;
    console.log('患者计加工', rowsList)

     // 修改
    const handleEditItem = (rowData: any) => {
      let id = rowData.customerId
      list.title = '修改计加工'
      list.openDrawer = 
      list.id = rowData.id
      list.customerId = rowData.customerId

      list.orderDetailId = rowData.orderDetailId
      list.medicalHistoryId = rowData.medicalHistoryId,
      list.processOrderCode = rowData.processOrderCode,
      list.consigneeId = rowData.consigneeId,
      list.companyUserId = rowData.companyUserId,
      list.processFactoryId = rowData.processFactoryId
      list.details = rowData.details
    }
    // 删除
    const handleDelItem = (rowData: any) => {
      let id = rowData.id
      ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        request.sendRequest({
          address: `/warehouse/processLog/processDelete/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
            ElMessage.success('删除成功')
            req()
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
          },
          method: "POST",
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      });
    }

    // 下拉
    const handleChange = (e: string, rowData: any) => {
      let id = rowData.id
      let val = JSON.parse(JSON.stringify(e))
      changeStatus(val, id)
    } 


    const search = () => {
      console.log('search')
    }

    // 点击新增记录
    const addRecord = () => {
      list.openDrawer = true

      list.title = '新建计加工'
      list.medicalHistoryId = ''
      list.processOrderCode = ''
      list.consigneeId = ''
      list.companyUserId = ''
      list.processFactoryId = ''
      list.orderDetailId = ''

      list.details = []
    }

    const close = () => {
      list.openDrawer = false
    }

    const cancel = () => {
      list.openDrawer = false
    }

    const save = () => {
      console.log('save')
      if(list.title === '新建计加工') {
        request.sendRequest({
        address: '/warehouse/processLog/processAdd',
        params: {
          customerId: id,
          medicalHistoryId: list.medicalHistoryId,
          processOrderCode: list.processOrderCode,
          consigneeId: list.consigneeId,
          companyUserId: list.companyUserId,
          processFactoryId: list.processFactoryId,
          details: list.details
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取供应商管理列表失败')
          ElMessage.success(resp.msg)

          close()
          req()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取供应商管理列表失败')
          
        },
        method: "POST",
      })
      }
      if(list.title === '修改计加工') {
        request.sendRequest({
        address: '/warehouse/processLog/processUpdate',
        params: {
          id: list.id,
          customerId: list.customerId,
          medicalHistoryId: list.medicalHistoryId,
          processOrderCode: list.processOrderCode,
          consigneeId: list.consigneeId,
          companyUserId: list.companyUserId,
          processFactoryId: list.processFactoryId,
          details: list.details
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          ElMessage.success(resp.msg)

          close()
          req()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
      }
    }

    const req = () => {
      list.loading = true
      let search = {
        current: list.current,
        size: list.size,
        customId: id
      }
      request.sendRequest({
        address: 'warehouse/processLog/processListByPage',
        params: search,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取供应商管理列表失败')
          list.data = resp.data.records
          list.total = resp.data.total
          list.current = resp.data.current

          list.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取供应商管理列表失败')
          
        },
        method: "POST",
      })

      
    }

    const getStatus = () => {
      request.sendRequest({
        address: '/warehouse/processLog/getTechnologyProcessStatus',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg )
          list.options = resp.data
          list.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    
    const changeStatus = (status: string, id: string | number) => {
      request.sendRequest({
        address: 'warehouse/processLog/processStatusUpdate',
        params: {
          id,
          status
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          ElMessage.success(resp.msg)
          req()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }

    const getDoctorList = () => {
      // 获取医生
      request.sendRequest({
        address: 'company/user/user/getDoctorUserByStatus',
        params: {
          name: ''
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          // console.log(resp.data)
          list.companyUserOptions = resp.data
          list.consigneeOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      }) 
    }

    const getHistorySelect = () => {
      //获取病历下拉
      request.sendRequest({
        address: 'sick/history/getHistorySelect',
        params: {
          customerId: id
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          // console.log(resp.data)
          list.medicalOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      }) 
    }

    const getTechnologyPlantList = () => {
      //获取加工厂下拉
      request.sendRequest({
        address: 'warehouse/processLog/getTechnologyPlantList',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          // console.log(resp.data)
          list.processFactoryOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      }) 
    }

    const getOrderDetail = () => {
      // 获取客户项目详情
      request.sendRequest({
        address: `/warehouse/processLog/getCustomOrderList/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          // console.log(resp.data)
          list.orderDetail = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      }) 
    }
      
    
    const addProcess = () => {
      console.log('新增了')
      list.details.push({
        orderDetailId: list.orderDetailId,
        processingItems: '默认',
        processingFree: 1
      })

      console.log(list.details)
    }
    const handleDelete = (index: number) => {
      console.log(index)
      list.details.splice(index, 1)
    }

    return {
      ...toRefs(list),
      search,
      addRecord,
      close,
      cancel,
      save,
      req,

      handleEditItem,
      handleDelItem,
      handleChange,
      getStatus,
      getDoctorList,
      getHistorySelect,
      getOrderDetail,
      getTechnologyPlantList,

      addProcess,
      handleDelete
    }
  }
})
</script>

<style lang="scss" scoped>
.machining {
  height: calc(100% - 40px);
  .machin-head {
    display: flex;
    align-items: center;
    height: 40px;
    line-height: 40px;
    padding: 0 20px 0 20px;
    border-bottom: 2px solid $mainColor;
    box-sizing: border-box;
    .machin-seach {
      display: flex;
      align-items: center;
      .machin-select {
        padding: 0 20px 0 10px;
      }
    }
    .machin-btn {
      flex: 1;
      text-align: right;
    }
  }
  .machin-content {
    height: calc(100% - 40px);
  }
}

.tem {
  height: 60px;
  padding: 0 10px;
  display: block;
  
  .tem-title {
    padding-bottom: 5px;
  }
}

.machin-select {
	margin-right: 8px;
}
</style>